import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Not, In, Like } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { ResultData } from 'src/common/utils/result';
import { CreateSettingsDto, UpdateSettingsDto, QuerySettingsDto } from './dto/settings.dto';
import { SettingsEntity } from './entities/settings.entity';
import { isEmpty } from 'src/common/utils';
@Injectable()
export class SettingsService {
  constructor(
    @InjectRepository(SettingsEntity)
    private readonly settingsEntityRep: Repository<SettingsEntity>,
  ) {}

  async create(createSettingsDto: CreateSettingsDto) {
    const res = await this.settingsEntityRep.save(createSettingsDto);
    return ResultData.ok(res);
  }

  async findAll(query: QuerySettingsDto) {
    const entity = this.settingsEntityRep.createQueryBuilder('entity');
    entity.where({ delFlag: '0' });
    if (!isEmpty(query.childId)) {
      entity.andWhere('entity.childId = :childId', { childId: query.childId });
    }
    if (!isEmpty(query.type)) {
      entity.andWhere('entity.type = :type', { type: query.type });
    }
    if (!isEmpty(query.repeatDays)) {
      entity.andWhere('entity.repeatDays = :repeatDays', { repeatDays: query.repeatDays });
    }
    if (!isEmpty(query.isDaily)) {
      entity.andWhere('entity.isDaily = :isDaily', { isDaily: query.isDaily });
    }
    if (!isEmpty(query.startHour)) {
      entity.andWhere('entity.startHour = :startHour', { startHour: query.startHour });
    }
    if (!isEmpty(query.startMinute)) {
      entity.andWhere('entity.startMinute = :startMinute', { startMinute: query.startMinute });
    }
    if (!isEmpty(query.endHour)) {
      entity.andWhere('entity.endHour = :endHour', { endHour: query.endHour });
    }
    if (!isEmpty(query.endMinute)) {
      entity.andWhere('entity.endMinute = :endMinute', { endMinute: query.endMinute });
    }
    if (!isEmpty(query.delFlag)) {
      entity.andWhere('entity.delFlag = :delFlag', { delFlag: query.delFlag });
    }
    if (!isEmpty(query.createTime)) {
      entity.andWhere('entity.createTime BETWEEN :start AND :end', { start: query.createTime[0], end: query.createTime[1] });
    }
    if (!isEmpty(query.updateTime)) {
      entity.andWhere('entity.updateTime BETWEEN :start AND :end', { start: query.updateTime[0], end: query.updateTime[1] });
    }
    entity.select(['entity.childId', 'entity.type', 'entity.repeatDays', 'entity.isDaily', 'entity.startHour', 'entity.startMinute', 'entity.endHour', 'entity.endMinute']);

    if (query.orderByColumn && query.isAsc) {
      const key = query.isAsc === 'ascending' ? 'ASC' : 'DESC';
      entity.orderBy(`entity.${query.orderByColumn}`, key);
    }

    if (query.pageNum && query.pageSize) {
      entity.skip(query.pageSize * (query.pageNum - 1)).take(query.pageSize);
    }

    const [list, total] = await entity.getManyAndCount();

    return ResultData.ok({
      list,
      total,
    });
  }

  async findOne(childId: number) {
    const res = await this.settingsEntityRep.findOne({
      where: {
        delFlag: '0',
        childId: childId,
      },
    });
    return ResultData.ok(res);
  }

  async update(updateSettingsDto: UpdateSettingsDto) {
    const res = await this.settingsEntityRep.update({ childId: updateSettingsDto.childId }, updateSettingsDto);
    return ResultData.ok({ value: res.affected >= 1 });
  }

  async remove(childIds: number[]) {
    const res = await this.settingsEntityRep.update(
      { childId: In(childIds) },
      {
        delFlag: '1',
      },
    );
    return ResultData.ok({ value: res.affected >= 1 });
  }

  async findUserByUsername(childId: number) {
    // 原生SQL（使用参数化查询，? 为占位符）
    const sql = `SELECT * FROM sys_user WHERE user_id = ? AND del_flag = 0`;

    // 执行查询：第二个参数是占位符对应的参数值（避免SQL注入）
    const result = await this.settingsEntityRep.query(sql, [childId]);

    // 返回查询结果（取第一个或null）
    return result.length > 0 ? result[0] : null;
  }

  async check(childId: number) {

    // 检查用户是否存在
    const user = await this.findUserByUsername(childId);
    if (!user) {
      return ResultData.fail(401, '用户不存在');
    }

    const setting = await this.settingsEntityRep.findOne({
      where: {
        delFlag: '0',
        childId: childId,
      },
    });

    if (!setting) {
      return ResultData.fail(500, '设置不存在');
    }

    // 获取当前时间
    const now = new Date();
    const currentHour = now.getHours();
    const currentMinute = now.getMinutes();

    if (setting.type === 1) {
      return ResultData.ok({ value: 1 });
    } else if (setting.type === 2) {
      return ResultData.ok({ value: 0 });
    } else if (setting.type === 3) {
      // 是否每日
      if (setting.isDaily === 1) {
        // 在 check 方法中可以这样调用
        if (this.isCurrentTimeInRange(setting.startHour, setting.startMinute, setting.endHour, setting.endMinute)) {
          return ResultData.ok({ value: 0 });
        } else {
          return ResultData.ok({ value: 1 });
        }
      } else {
        const repeatDays = setting.repeatDays.split(',');

        // 检查是否在重复日期范围内
        if (repeatDays.includes(String(now.getDay()))) {
          // 在 check 方法中可以这样调用
          if (this.isCurrentTimeInRange(setting.startHour, setting.startMinute, setting.endHour, setting.endMinute)) {
            return ResultData.ok({ value: 0 });
          } else {
            return ResultData.ok({ value: 1 });
          }
        } else {
          return ResultData.ok({ value: 1 });
        }
      }
    }

    return ResultData.ok({ value: 0 });
  }

  /**
   * 检查当前时间是否在指定的时间范围内
   * @param startHour 开始小时
   * @param startMinute 开始分钟
   * @param endHour 结束小时
   * @param endMinute 结束分钟
   * @returns boolean 是否在时间范围内
   */
  private isCurrentTimeInRange(startHour: number, startMinute: number, endHour: number, endMinute: number): boolean {
    // 获取当前中国时区时间
    const now = new Date();
    const chinaTime = new Date(now.getTime() + 8 * 60 * 60 * 1000);
    console.log(chinaTime);

    // 构建开始时间（当天）
    const startTime = new Date(chinaTime);
    startTime.setUTCHours(startHour, startMinute, 0, 0);
    console.log(startTime);

    // 构建结束时间（当天）
    const endTime = new Date(chinaTime);
    endTime.setUTCHours(endHour, endMinute, 0, 0);
    console.log(endTime);

    // 使用中国时区时间进行比较
    return chinaTime >= startTime && chinaTime <= endTime;
  }
}
